<template>
  <div>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
      <el-form-item label="单据编号" prop="docNo">
        <el-input
            v-model="queryParams.docNo"
            placeholder="请输入单据编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="老人姓名" prop="elderName">
        <el-input
            v-model="queryParams.elderName"
            placeholder="请输入老人姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="老人身份证号" prop="elderIdCard">
        <el-input
            v-model="queryParams.elderIdCard"
            placeholder="请输入老人身份证号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="请假开始时间" prop="leaveStart">
        <el-date-picker
            clearable
            v-model="queryParams.leaveStart"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择请假开始时间"
        />
      </el-form-item>
      <el-form-item label="预计返回时间" prop="expectedReturn">
        <el-date-picker
            clearable
            v-model="queryParams.expectedReturn"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择预计返回时间"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 分隔线 + 状态筛选+按钮区域（flex 布局） -->
    <el-divider></el-divider>
    <div class="filter-bar">
      <!-- 左侧状态标签 -->
      <div class="status-tabs-area">
        <el-tabs
            v-model="currentStatus"
            @tab-click="handleStatusClick"
            type="card"
            class="custom-status-tabs"
        >
          <el-tab-pane label="全部" name="全部"></el-tab-pane>
          <el-tab-pane label="请假中" name="0"></el-tab-pane>
          <el-tab-pane label="超时未归" name="1"></el-tab-pane>
          <el-tab-pane label="已返回" name="2"></el-tab-pane>
        </el-tabs>
      </div>
      <!-- 右侧发起申请按钮 -->
      <div class="add-btn-area">
        <el-button type="primary" @click="createLeaveRequest">发起请假申请</el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="leaveRequestList">
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="单据编号" align="center" prop="docNo" />
      <el-table-column label="老人姓名" align="center" prop="elderName" />
      <el-table-column label="老人身份证号" align="center" prop="elderIdCard" />
      <el-table-column label="请假开始时间" align="center" prop="leaveStart" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.leaveStart, '{y}-{m}-{d} {h}:{s}:{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预计返回时间" align="center" prop="expectedReturn" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expectedReturn, '{y}-{m}-{d} {h}:{s}:{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际返回时间" align="center" prop="actualReturn" width="180">
        <template #default="scope">
          <span v-if="scope.row.actualReturn">{{ parseTime(scope.row.actualReturn, '{y}-{m}-{d} {h}:{s}:{m}') }}</span>
          <span v-else>— —</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createName" />
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{s}:{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请假状态" align="center" prop="leaveStatus">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row)">{{ getStatusText(scope.row) }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              link
              type="primary"
              v-hasPermi="['residing:leaveRequest:edit']"
              @click="openReturnDialog(scope.row)"
              :disabled="!!scope.row.actualReturn"
          >返回</el-button>
          <el-button
              link
              type="primary"
              v-hasPermi="['residing:leaveRequest:query']"
              @click="handleView"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </div>


  <!-- 填写返回信息的对话框 -->
  <el-dialog
      title="填写返回信息"
      v-model="dialogVisible"
      width="500px"
      :before-close="handleDialogClose"
  >
    <el-form
        ref="returnFormRef"
        :model="returnForm"
    :rules="formRules"
    label-width="120px"
    >
    <!-- 请假开始时间（只读） -->
    <el-form-item label="请假开始时间">
      <el-input
          v-model="returnForm.leaveStart"
          readonly
          placeholder="无"
      />
    </el-form-item>

    <!-- 实际返回时间 -->
    <el-form-item label="实际返回时间" prop="actualReturn">
      <el-date-picker
          v-model="returnForm.actualReturn"
      type="datetime"
      format="YYYY-MM-DD HH:mm:ss"
      value-format="YYYY-MM-DD HH:mm:ss"
      placeholder="选择实际返回时间"
      clearable
      />
    </el-form-item>

    <!-- 请假天数（自动计算） -->
    <el-form-item label="请假天数" prop="actualLeaveDays">
      <el-input
          v-model.number="returnForm.actualLeaveDays"
      placeholder="自动计算中..."
      type="number"
      step="0.5"
      readonly
      />
    </el-form-item>

    <!-- 备注 -->
    <el-form-item label="备注" prop="remark">
      <el-input
          v-model="returnForm.remark"
      type="textarea"
      maxlength="50"
      show-word-limit
      rows="2"
      />
    </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleFormSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
  </div>
</template>

<script setup name="LeaveRequest">
import { listLeaveRequest,updateLeaveRequest } from "@/api/residing/leaveRequest";
import { ref, reactive, toRefs, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';
import {parseTime} from "../../../utils/ruoyi.js";

const { proxy } = getCurrentInstance();
const router = useRouter()

// 表格数据、加载状态、总条数
const leaveRequestList = ref([]);
const loading = ref(true);
const total = ref(0);
// 对话框显示状态
const dialogVisible = ref(false);
// 表单引用
const returnFormRef = ref(null);
// 存储当前行的请假开始时间（用于计算）
const leaveStart = ref('');


// 表单数据（对象名改为 returnForm）
const returnForm = reactive({
  id: '',
  elderId: '',
  leaveStart: '',         // 请假开始时间（展示用）
  actualReturn: '',       // 实际返回时间
  actualLeaveDays: null,  // 请假天数（自动计算）
  remark: '',              // 备注
  leaveStatus:'2'
});

// 表单校验规则
const formRules = reactive({
  actualReturn: [
    { required: true, message: '请选择实际返回时间', trigger: 'change' }
  ],
  actualLeaveDays: [
    { required: true, message: '请假天数不能为空', trigger: 'blur' },
    { type: 'number', min: 0.5, message: '请假天数不能小于0.5天', trigger: 'blur' }
  ]
});

// 当前选中的状态标签（默认“全部”）
const currentStatus = ref('全部');

// 响应式数据：查询参数、表单、校验规则
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    docNo: null,
    elderName: null,
    elderIdCard: null,
    leaveStart: null,
    expectedReturn: null,
    leaveStatus: null,
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);


// 转换 YYYY-MM-DD 为当天 23:59:59
const getEndOfDay = (dateStr) => {
  if (!dateStr) return new Date(0);
  const [year, month, day] = dateStr.split('-').map(Number);
  return new Date(year, month - 1, day, 23, 59, 59);
};

//查看按钮
const handleView = () => {
  router.push({
    name: 'LeaveResult'
  })
}

// 打开返回对话框
const openReturnDialog = (row) => {
  returnFormRef.value?.resetFields();
  returnForm.id = row.id
  returnForm.elderId = row.elderId,
  leaveStart.value = parseTime(row.leaveStart, '{y}-{m}-{d} {h}:{s}:{m}'); // 存储请假开始时间
  returnForm.leaveStart = leaveStart.value || '无'; // 回显开始时间
  // 重置表单
  returnForm.actualReturn = '';
  returnForm.actualLeaveDays = null;
  returnForm.remark = '';
  dialogVisible.value = true;
};

// 监听实际返回时间变化，自动计算天数
watch(
    () => returnForm.actualReturn,
    (newVal) => {
      if (!newVal || !leaveStart.value) {
        returnForm.actualLeaveDays = null;
        return;
      }
      returnForm.actualLeaveDays = calculateLeaveDays(leaveStart.value, newVal);
    }
);

// 计算请假天数（核心逻辑）
const calculateLeaveDays = (startStr, endStr) => {
  const startTime = new Date(startStr);
  const endTime = new Date(endStr);

  if (isNaN(startTime.getTime()) || isNaN(endTime.getTime())) {
    ElMessage.error('时间格式无效');
    return null;
  }
  if (endTime <= startTime) {
    ElMessage.error('返回时间不能早于开始时间');
    return null;
  }

  // 计算小时差 → 按12小时递增0.5天规则转换
  const hourDiff = (endTime - startTime) / (1000 * 60 * 60);
  return Math.ceil(hourDiff / 12) * 0.5;
};

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false;
};

// 提交表单
const handleFormSubmit = async () => {
  try {
    await returnFormRef.value.validate();
    // 提交逻辑（示例）
    console.log('提交返回信息：', returnForm);
    //提交表单
    await updateLeaveRequest(returnForm).then(res =>{
      proxy.$modal.msgSuccess("修改成功")
      dialogVisible.value = false;
      getList()
    })
  } catch (error) {
    ElMessage.error('请完善表单信息');
  }
};


/**
 * 生成请假状态的 Tag 类型（控制标签颜色）
 * @param {Object} row - 行数据（含 actualReturn、expectedReturn）
 * @returns {string} Element Plus Tag 类型（success/danger/info）
 */
const getStatusTagType = (row) => {
  const now = new Date();
  const actualReturn = row.actualReturn;
  const expectedReturn = row.expectedReturn;
  const expectedEndTime = getEndOfDay(expectedReturn);

  if (actualReturn) {
    return 'success'; // 已返回 → 绿色标签
  } else if (now > expectedEndTime) {
    if (row.leaveStatus == '0'){
      updateLeaveRequest({id: row.id, leaveStatus: '1'}).then(res =>{
        proxy.$modal.msgSuccess("修改成功")
        getList()
      })
    }
    return 'danger'; // 超时未归 → 红色标签
  } else {
    return 'info'; // 请假中 → 蓝色标签
  }
};



/**
 * 生成请假状态的显示文本
 * @param {Object} row - 行数据
 * @returns {string} 状态文本（已返回/超时未归/请假中）
 */
const getStatusText = (row) => {
  const now = new Date();
  const actualReturn = row.actualReturn;
  const expectedReturn = row.expectedReturn;
  const expectedEndTime = getEndOfDay(expectedReturn);

  if (actualReturn) {
    return '已返回';
  } else if (now > expectedEndTime) {
    return '超时未归';
  } else {
    return '请假中';
  }
};

// 发起请假申请
const createLeaveRequest = () => {
  console.log("发起请假申请")
  router.push({
    name: 'LeaveRequestForm', // 对应路由配置中的name
  })
}

/** 查询请假列表（带状态筛选） */
function getList() {
  loading.value = true;
  listLeaveRequest(queryParams.value).then(response => {
    leaveRequestList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    console.log(leaveRequestList.value)
  });
}

/** 搜索按钮：重置页码 + 查新列表 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮：重置表单 + 触发搜索 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.leaveStatus = currentStatus.value === '全部' ? null : currentStatus.value;
  handleQuery();
}

/** 状态标签切换：更新筛选参数 + 查新列表 */
const handleStatusClick = (tab) => {
  console.log(tab.props.name); // 此时可正常获取name
  queryParams.value.leaveStatus = tab.props.name === '全部' ? null : tab.props.name;
  queryParams.value.pageNum = 1;
  getList();
};

/** 发起请假申请 */
function handleAdd() {
  console.log('发起请假申请');
}

// 初始化加载列表
getList();
</script>

<style scoped>
/* 筛选栏 flex 布局 */
.filter-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

/* 左侧状态标签容器 */
.status-tabs-area {
  display: flex;
  align-items: center;
  flex: 1;
}

/* 自定义状态标签：确保选中标签底部边框显示 */
::v-deep .custom-status-tabs {
  width: fit-content;
}

::v-deep .custom-status-tabs .el-tabs__nav-wrap {
  margin: 0;
}

/* 所有标签底部先设置透明边框（占位） */
::v-deep .custom-status-tabs .el-tabs__item {
  padding: 6px 14px;
  font-size: 14px;
  border-bottom: 2px solid transparent; /* 透明边框占位 */
}

/* 选中标签：底部显示蓝色边框 */
::v-deep .custom-status-tabs .el-tabs__item.is-active {
  border-bottom-color: #409eff !important; /* 覆盖透明色，显示蓝色 */
  color: #409eff;
}

/* 右侧按钮容器 */
.add-btn-area {
  display: flex;
  align-items: center;
}
</style>